import 'dart:convert';
import 'dart:io';

import 'package:fbutton/fbutton.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/home/wifi/bean_client.dart';
import 'package:flutter_chip/view/home/wifi/data_utils.dart';
import 'package:flutter_chip/widget/view_checkbox.dart';
import 'package:fsuper/fsuper.dart';

import '../widget_period.dart';

class ClientPage extends StatefulWidget {
  @override
  _ClientPageState createState() => _ClientPageState();
}

class _ClientPageState extends State<ClientPage>
    with AutomaticKeepAliveClientMixin {
  ///ip：port输入框
  var _ipController = TextEditingController();
  var _portController = TextEditingController();
  var _sendController = TextEditingController();
  var _recvController = ScrollController();

  Client _client = Client();

  ///重连次数
  int count = 0;

  ///数据流
  Stream<List<int>> _stream;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          _currClient(),
          _recvWidget(),
          _sendWidget(),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _ipController.dispose();
    _portController.dispose();
    _recvController.dispose();
    if (null != _client && null != _client.socket) {
      _client.socket.destroy();
    }
  }

  ///头部
  Widget _currClient() {
    return FSuper(
      width: Comm.screenWidth,
      height: 40,
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.only(left: 10),
      child1: FSuper(
        height: 40,
        width: Comm.screenWidth,
        text: _client.clientIp.isEmpty
            ? '未连接'
            : '已连接：${_client.clientIp}:${_client.clientPort}',
        textSize: 16,
        textColor: Colors.grey,
        textAlignment: Alignment.centerLeft,
        backgroundColor: Color(0xffDEDEDE),
        padding: EdgeInsets.only(left: 10),
        corner: Corner.all(6),
        child1: Icon(Icons.edit, color: Colors.grey),
        child1Margin: EdgeInsets.only(right: 6),
        child1Alignment: Alignment.centerRight,
      ),
      child1Margin: EdgeInsets.only(right: 30, left: 30),
      child1Alignment: Alignment.centerLeft,
      onChild1Click: addServer,
    );
  }

  ///数据接收区
  Widget _recvWidget() {
    return FSuper(
      width: double.infinity,
      height: 240,
      margin: EdgeInsets.only(left: 10, right: 10),
      text: "数据接收区",
      textColor: Colors.grey,
      padding: EdgeInsets.all(6),
      textAlignment: Alignment.topLeft,
      textAlign: TextAlign.left,
      child1Margin: EdgeInsets.only(top: 10),
      backgroundColor: Color(0xffEEEEEE),
      corner: Corner.all(6),
      child1: Container(
        width: Comm.screenWidth - 110,
        height: 216,
        margin: EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 10),
        child: ListView(
          controller: _recvController,
          children: <Widget>[
            Text(_client.recvData),
          ],
        ),
      ),
      child1Alignment: Alignment.centerLeft,
      child2Alignment: Alignment.bottomRight,
      child2: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          FSuper(
            width: 84,
            height: 24,
            text: 'TX：${_client.txNum}',
            textAlignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 10),
          ),
          FSuper(
            width: 84,
            height: 24,
            text: 'RX：${_client.rxNum}',
            textAlignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 10),
          ),
          FSuper(
            height: 32,
            width: 76,
            text: "计数清零",
            textSize: 12,
            textAlignment: Alignment.center,
            backgroundColor: Color(0xffDDDDDD),
            corner: Corner.all(6),
            onClick: () {
              setState(() {
                _client.rxNum = 0;
                _client.txNum = 0;
              });
            },
          ),
          Container(child: Divider(), width: 84),
          MyCheckBox(
            "自动换行",
            _client.autoLine,
            (value) => _client.autoLine = value,
          ),
          SizedBox(height: 6),
          MyCheckBox(
            "HEX显示",
            _client.showHex,
            (value) => _client.showHex = value,
          ),
          SizedBox(height: 6),
          FSuper(
            height: 32,
            width: 76,
            text: "清除显示",
            textSize: 12,
            textAlignment: Alignment.center,
            backgroundColor: Color(0xffDDDDDD),
            corner: Corner.all(6),
            onClick: () => setState(() => _client.recvData = ''),
          ),
          SizedBox(height: 6),
        ],
      ),
    );
  }

  ///发送数据
  Widget _sendWidget() {
    return FSuper(
      width: double.infinity,
      height: 110,
      text: '数据发送区',
      textColor: Colors.grey,
      backgroundColor: Color(0xFFEEEEEE),
      corner: Corner.all(6),
      textAlignment: Alignment.topLeft,
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      padding: EdgeInsets.only(left: 6, top: 6),
      child1Margin: EdgeInsets.only(bottom: 8),
      child1: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          MyCheckBox(
            "HEX发送",
            _client.sendHex,
            (value) => _client.sendHex = value,
          ),
          MyCheckBox(
            "自动发送",
            _client.autoSend,
            (value) => _client.autoSend = value,
          ),
          PeriodWidget(
            _client.period,
            (period) => _client.period = period,
          ),
        ],
      ),
      child2: FSuper(
        width: double.infinity,
        height: 36,
        child1: Container(
          width: Comm.screenWidth - 84,
          height: 36,
          child: TextField(
            controller: _sendController,
            decoration: InputDecoration(
              hintText: "发送数据",
              hintStyle: TextStyle(fontSize: 12),
              contentPadding: EdgeInsets.all(10),
              border: OutlineInputBorder(
                borderSide: BorderSide(),
                borderRadius: BorderRadius.all(Radius.circular(6)),
              ),
            ),
          ),
        ),
        child1Margin: EdgeInsets.only(left: 6),
        child2Margin: EdgeInsets.only(right: 6),
        child1Alignment: Alignment.centerLeft,
        child2Alignment: Alignment.centerRight,
        child2: FButton(
          onPressed: _sendData,
          width: 48,
          height: 36,
          padding: EdgeInsets.zero,
          text: '发送',
          fontSize: 12,
          textColor: Colors.white,
          corner: FButtonCorner.all(4),
          effect: true,
          clickEffect: true,
          color: Theme.of(context).accentColor,
        ),
      ),
      child2Margin: EdgeInsets.only(bottom: 6),
      child2Alignment: Alignment.bottomCenter,
    );
  }

  ///添加服务器IP:PORT
  void addServer() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('添加服务器'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                TextField(
                  controller: _ipController,
                  decoration: InputDecoration(
                    labelText: "IP地址",
                    hintText: "请输入IP地址",
                    hintStyle: TextStyle(fontSize: 12),
                    contentPadding: EdgeInsets.all(10),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(),
                      borderRadius: BorderRadius.all(Radius.circular(6)),
                    ),
                  ),
                ),
                SizedBox(height: 6),
                TextField(
                  controller: _portController,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    labelText: "端口号",
                    hintText: "请输入端口号",
                    hintStyle: TextStyle(fontSize: 12),
                    contentPadding: EdgeInsets.all(10),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(),
                      borderRadius: BorderRadius.all(Radius.circular(6)),
                    ),
                  ),
                ),
              ],
            ),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text("取消"),
              ),
              FlatButton(
                onPressed: () {
                  if (_ipController.text.isEmpty) {
                    Toast.show("请输入IP地址");
                    return;
                  }
                  if (_portController.text.isEmpty) {
                    Toast.show("请输入端口号");
                    return;
                  }
                  setState(() {
                    _client.clientIp = _ipController.text;
                    _client.clientPort = int.parse(_portController.text);
                  });
                  initSocket();
                  Navigator.pop(context);
                },
                child: Text("确定"),
              ),
            ],
          );
        });
  }

  ///初始化Socket
  void initSocket() async {
    if (null != _client && null != _client.socket) {
      _client.socket.close();
      _client.socket = null;
    }
    await Socket.connect(_client.clientIp, _client.clientPort)
        .then((Socket socket) {
      Toast.show('连接成功');
      count = 0;
      _client.socket = socket;
      _stream = _client.socket.asBroadcastStream();
    }).catchError((error) {
      count++;
      print('连接异常：$count-----${error.toString()}');
      if (count < 10) {
        initSocket();
      } else {
        Toast.show('连接失败');
      }
    });
    _stream.listen((data) {
      _client.rxNum += data.length;
      print('原始数据：$data');
      try {
        String recv = '';
        if (_client.showHex) {
          data.forEach((byte) {
            recv += '${byte.toRadixString(16).toUpperCase()} ';
          });
        } else {
          recv = '${ascii.decode(data)}';
        }
        setState(() {
          _client.recvData += '$recv${_client.autoLine ? '\n' : ''}';
        });
        _recvController.jumpTo(_recvController.position.maxScrollExtent);
      } on FormatException catch (error) {
        Toast.show('只接受Ascii字符');
        print(error.toString());
      }
    }).onDone(() {
      print("连接已断开");
      Toast.show('连接已断开');
      if (!mounted) {
        setState(() {
          _client.clientIp = '';
          _client.clientPort = -1;
        });
      }
    });
  }

  ///发送数据
  void _sendData() {
    if (_sendController.text.isEmpty) {
      Toast.show('请输入发送内容');
      return;
    }
    if (null == _client.socket) {
      Toast.show('请先连接服务器');
      return;
    }
    String sendStr = _sendController.text;
    if (_client.sendHex) {
      List<int> hexs = List();
      List<String> tmpList = sendStr.split(' ');
      try {
        tmpList.forEach((hexData) {
          int tmpData = DataUtils.hexToInt(hexData);
          hexs.add(tmpData);
        });
        print('发送原始值：$hexs');
        _client.txNum += hexs.length;
        _client.socket.add(hexs);
      } catch (e) {
        Toast.show('请输入正确16进制值，不包含0X，多个用空格隔开');
      }
    } else {
      _client.txNum += ascii.encode(sendStr).length;
      _client.socket.add(ascii.encode(sendStr));
    }
    setState(() {});
    if (_client.autoSend) {
      Future.delayed(Duration(milliseconds: _client.period))
          .then((value) => _sendData());
    }
  }

  @override
  bool get wantKeepAlive => true;
}
